package com.winterwar.web;

import java.net.InetSocketAddress;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.spy.memcached.MemcachedClient;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;

import com.winterwar.base.Table;
import com.winterwar.service.ConventionManager;
import com.winterwar.service.TableManager;

public class TableAction  extends DispatchAction{
	
	private static Log log = LogFactory.getLog(TableAction.class);
	private TableManager mgr;
	private ConventionManager conMgr;
	
	public void setConventionManager(ConventionManager mgr){
		this.conMgr = mgr;
	}
	
	public void setManager(TableManager mgr){
		this.mgr = mgr;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting delete...");
		}
		mgr.remove(request.getParameter("table.id"));
		ActionMessages messages = new ActionMessages();
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("table.deleted"));
		saveMessages(request, messages);
		return list(mapping, form, request, response);
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting save...");
		}
		Random gen = new Random(new Date().getTime());
		HttpSession session = request.getSession();
		
		if(session.getAttribute("randFormID").toString().equals(request.getParameter("formID").toString())){
			session.setAttribute("randFormID", gen.nextInt() + "");
			Table table = new Table();
			String tableID = request.getParameter("table.tableID");
			if(tableID != null && tableID.length() > 0 && tableID.compareTo("") != 0)
				table.setTableID(Integer.valueOf(tableID));
			else
				table.setTableID(null);
			table.setTableName(request.getParameter("table.tableName"));
			table.setPhysicalTables(Integer.valueOf(request.getParameter("table.physicalTables")));
			String conID = request.getParameter("conID");
			MemcachedClient cacheClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));
			if(conID == null || conID.compareTo("") == 0 || conID.length() < 1){
				conID = (cacheClient.get("Curr_Con_ID") != null) ? cacheClient.get("Curr_Con_ID").toString() : null;;
				if(conID == null || conID.equals("")){
					conID = conMgr.getCurrentCon().getConID().toString();
					cacheClient.set("Curr_Con_ID", 86400, conID);
				}
			}
			table.setConID(Integer.valueOf(conID));
			
			mgr.save(table);
			
			ActionMessages messages = new ActionMessages();
			messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("table.saved"));
			saveMessages(request, messages);
		}
		return list(mapping, form, request, response);
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form,
					HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting edit...");
		}
		DynaActionForm tableForm = (DynaActionForm) form;
		String tableID = request.getParameter("tableID");
		request.setAttribute("conID", request.getParameter("conID"));
		
		if(tableID != null){
			Table table = mgr.get(tableID);
			if(table == null){
				ActionMessages errors = new ActionMessages();
				errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("table.missing"));
				saveErrors(request, errors);
				
				return mapping.findForward("list");
			}
			tableForm.set("table", table);
		}
		return mapping.findForward("edit");
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
						HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		request.setAttribute("tables", mgr.getAll());
		
		return mapping.findForward("list");
	}
	
	public ActionForward listByCon(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		String conID = request.getParameter("conID");
		MemcachedClient cacheClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));
		if(conID == null){
			conID = (cacheClient.get("Curr_Con_ID") != null) ? cacheClient.get("Curr_Con_ID").toString() : null;;
			if(conID == null || conID.equals("")){
				conID = conMgr.getCurrentCon().getConID().toString();
				cacheClient.set("Curr_Con_ID", 86400, conID);
			}
		}
		request.setAttribute("conID", conID);
		request.setAttribute("tables", mgr.getAllByCon(conID));
		
		return mapping.findForward("list");
	}
}
